import './index.scss'

import { Divider, Table, Space, Switch, Button, Col, Form, Input, Row, Select, theme, DatePicker, Pagination, Modal, message, List, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import { goods } from '../../../utils/sendRequst'
import { omit } from '../../../utils/sendRequst'
import { increase } from '../../../utils/sendRequst'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

const Student = () => {

    // 图片头像函数
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const handleChange = (info) => {

        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg';
        if (!isJpgOrPng) {
            return message.error('图片后缀格式不对');
        }
        const isLt2M = info.file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            return message.error('最大只能上传2m的图片');
        }
        // 将文件对象转换格式
        getBase64(info.file.originFileObj, (url) => {
            setImageUrl(url);
        })
    };
    
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );






    const [form] = Form.useForm();

    //这是专区渲染
    const [dataList, SetDataList] = useState([]);
    const [list, SetList] = useState([])


    //添加的模态框
    const [isModalOpen2, setIsModalOpen2] = useState(false);





    //获取商品数据
    const getStu = () => {
        goods().then(res => {
            const list = res.data.map(item => ({ ...item, key: item.productID }))
            SetDataList(list)
        })

    };

    //添加确定取消的模态框
    const onFinishok2 = (values) => {
      
        const formData = new FormData();
        formData.append('file', values.productUrl.file.originFileObj);
        fetch('/api/upload', {
          method: 'POST',
          body: formData
        })
        .then(res => {
        //   console.log(res.status); // 打印 HTTP 响应状态码
          return res.text(); // 将响应转换为文本
        })
        .then(text => {
        //   console.log(text); // 打印文本响应
          const imageUrl = text.trim(); // 去除文本响应中的空白字符
          values.productUrl = imageUrl; // 将服务器返回的文件路径设置到 表单值values.productUrl 中
          increase(values).then(res => {
            if (res && res.code === 200) {
              getStu();
              message.success("添加成功");
              setImageUrl(null);
            } else {
              message.error("添加失败");
              setImageUrl(null);
            }
          });
          setIsModalOpen2(false);
        })
        .catch(err => {
        //   console.error(err); // 打印错误信息
          message.error("添加失败");
          setIsModalOpen2(false);
        });
      };
    //添加取消的模态框

    //添加确定后出现的模态框
    const addTo = () => {
        setIsModalOpen2(true);
    }




    //删除
    const shanChu = (row) => {
        console.log(row);
        if (row.productGrounding == 1 ) {
            message.success("当前商品已上架不可删除")
        } else {
            omit(row).then(res => {
                if (res.code == 200) {
                    getStu();
                    message.success("删除成功")
                } else {
                    message.success("删除失败")
                }
            })
        }
    }


    const columns = [
        {
            title: '序号',
            dataIndex: 'productID',
        },
        {
            title: '商品图片',
            render: (_, record) => (
                <Space size="middle">
                    < img src={'/api' + record.productUrl} alt="" />
                </Space>
            ),
        },
        {
            title: '商品名称',
            dataIndex: 'productName',
        },
        {
            title: '价格',
            dataIndex: 'productPrice',
        },
        {
            title: '是否上架',
            dataIndex: 'productGrounding',
            render: (text, record, index) => {
                return (
                    <Switch defaultChecked={record.productGrounding}
                        disabled
                        checked={record.productGrounding}
                    />
                );
            },

        },
        {
            title: '操作',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => {
                        shanChu(record)
                    }} >删除</a>
                </Space>
            ),
        },
    ];




    //获取商品数据
    useEffect(() => {
        getStu()
    }, [])

    //表格
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            name: record.name,
        }),
    };

    const onSwitchChange = (checkedValue) => {
        SetList((prevState) => ({
          ...prevState,
          productGrounding: checkedValue
        }));
      };

      

    return (
        <div>
            <div className='btn-1'>
                <div className='btn-a'>
                    <p className='btn-b'>商品列表</p>
                    <p className='btn-c' onClick={addTo}>添加商品</p>
                </div>
            </div>
            <Table pagination={{ pageSize: 5 }} rowSelection={{
                ...rowSelection,
            }}
                columns={columns}
                dataSource={dataList}
            />
            <Divider />

            {/* 添加的模态框 */}
            <>
                <Modal title="添加商品" open={isModalOpen2} footer={null} closable={false} destroyOnClose={true} >
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        onFinish={onFinishok2}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="商品图片"
                            name="productUrl"
                            rules={[{ required: true, message: '商品图片必选' }]}
                        >
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                // beforeUpload={beforeUpload}
                                onChange={handleChange}
                               
                            >
                                {imageUrl ? (
                                    <img
                                        src={imageUrl}
                                        alt="avatar"
                                        style={{
                                            width: '100%',
                                            height:'80%'
                                        }}
                                    />
                                ) : (uploadButton)}
                            </Upload>
                        </Form.Item>


                        <Form.Item
                            label="商品名称"
                            name="productName"
                            rules={[{ required: true, message: '输入商品名称' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label='价格'
                            name="productPrice"
                            rules={[{ required: true, message: '输入商品价格' }]}
                        >
                            <Input />

                        </Form.Item>

                        <Form.Item
                            label='是否上架'
                            name="productGrounding"
                        >
                            <Switch  onChange={(checkedValue) => onSwitchChange(checkedValue)} />

                        </Form.Item>


                        <Form.Item>
                            <Button type="primary" htmlType="submit" className='btn' onClick={() => {
                                form.resetFields();
                            }} >
                                确定
                            </Button>
                            <Button type="default" onClick={() => {
                                form.resetFields();
                                setIsModalOpen2(false);
                            }}>
                                取消
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </>

        </div>
    );
}

export default Student;